#!/usr/bin/env python3
"""
Build script for AI-Powered SSH Terminal
Uses PyInstaller to create standalone executables
"""

import os
import sys
import subprocess
import shutil
import platform
from pathlib import Path
import argparse

def check_dependencies():
    """Check if required build dependencies are installed"""
    print("🔍 Checking build dependencies...")
    
    required_packages = ['pyinstaller', 'setuptools']
    missing_packages = []
    
    for package in required_packages:
        try:
            __import__(package)
            print(f"✓ {package}")
        except ImportError:
            missing_packages.append(package)
            print(f"❌ {package}")
    
    if missing_packages:
        print(f"\n⚠️  Missing packages: {', '.join(missing_packages)}")
        print("Install with:")
        if 'CONDA_DEFAULT_ENV' in os.environ:
            print(f"   conda install {' '.join(missing_packages)}")
        else:
            print(f"   pip install {' '.join(missing_packages)}")
        return False
    
    print("✓ All build dependencies are available")
    return True

def clean_build_dirs():
    """Clean previous build directories"""
    print("\n🧹 Cleaning previous builds...")
    
    dirs_to_clean = ['build', 'dist', '__pycache__']
    
    for dir_name in dirs_to_clean:
        if Path(dir_name).exists():
            shutil.rmtree(dir_name)
            print(f"✓ Removed {dir_name}/")
    
    # Clean .pyc files
    for pyc_file in Path('.').rglob('*.pyc'):
        pyc_file.unlink()
    
    print("✓ Build directories cleaned")

def check_ollama_service():
    """Check if Ollama service is available"""
    try:
        import requests
        response = requests.get("http://localhost:11434/api/tags", timeout=2)
        if response.status_code == 200:
            models = response.json().get('models', [])
            print(f"✓ Ollama service running with {len(models)} models")
            return True, len(models)
        else:
            print("⚠️  Ollama service not responding")
            return False, 0
    except Exception as e:
        print(f"⚠️  Ollama service not available: {e}")
        print("   Install Ollama from: https://ollama.ai/")
        return False, 0

def update_spec_file(build_type='dir'):
    """Update spec file with current configuration"""
    print(f"\n⚙️  Updating spec file configuration...")
    
    spec_file = Path('ai_terminal.spec')
    if not spec_file.exists():
        print("❌ Spec file not found!")
        return False
    
    # Read current spec file
    content = spec_file.read_text(encoding='utf-8')
    
    # Update build type (onefile vs directory)
    if build_type == 'onefile':
        # Enable onefile build
        content = content.replace('"""', '', 2)  # Uncomment onefile section
    
    # Write updated spec file
    spec_file.write_text(content, encoding='utf-8')
    print("✓ Spec file updated")
    return True

def build_executable(build_type='dir', clean=True):
    """Build the executable using PyInstaller"""
    print(f"\n🔨 Building executable ({build_type} mode)...")
    
    if clean:
        clean_build_dirs()
    
    # Build command
    cmd = [
        sys.executable, '-m', 'PyInstaller',
        '--clean',
        'ai_terminal.spec'
    ]
    
    # Add additional flags
    if build_type == 'debug':
        cmd.extend(['--debug', 'all'])
    
    print(f"Running: {' '.join(cmd)}")
    
    try:
        result = subprocess.run(cmd, check=True, capture_output=False)
        print("\n✅ Build completed successfully!")
        return True
        
    except subprocess.CalledProcessError as e:
        print(f"\n❌ Build failed with exit code {e.returncode}")
        return False

def create_distribution_package():
    """Create a distribution package with documentation"""
    print("\n📦 Creating distribution package...")
    
    dist_dir = Path('dist')
    if not dist_dir.exists():
        print("❌ No dist directory found. Build first.")
        return False
    
    # Create package directory
    package_dir = Path('AI-Terminal-Package')
    if package_dir.exists():
        shutil.rmtree(package_dir)
    
    package_dir.mkdir()
    
    # Copy executable
    exe_dir = dist_dir / 'AI-Terminal'
    if exe_dir.exists():
        shutil.copytree(exe_dir, package_dir / 'AI-Terminal')
    
    # Copy documentation and configuration
    files_to_copy = [
        'README.md',
        'environment.yml',
        'requirements.txt',
        'setup_conda.bat',
        'setup_conda.sh'
    ]
    
    for file_name in files_to_copy:
        file_path = Path(file_name)
        if file_path.exists():
            shutil.copy2(file_path, package_dir)
    
    # Create startup scripts
    create_startup_scripts(package_dir)
    
    print(f"✅ Distribution package created: {package_dir}")
    return True

def create_startup_scripts(package_dir):
    """Create convenient startup scripts"""
    
    # Windows batch file
    batch_content = '''@echo off
echo Starting AI-Powered SSH Terminal...
cd /d "%~dp0"
AI-Terminal\\AI-Terminal.exe
pause
'''
    
    (package_dir / 'Start-AI-Terminal.bat').write_text(batch_content)
    
    # Unix shell script
    shell_content = '''#!/bin/bash
echo "Starting AI-Powered SSH Terminal..."
cd "$(dirname "$0")"
./AI-Terminal/AI-Terminal
'''
    
    shell_script = package_dir / 'start-ai-terminal.sh'
    shell_script.write_text(shell_content)
    shell_script.chmod(0o755)

def show_build_info():
    """Show information about the built executable"""
    print("\n📋 Build Information:")
    print(f"   Platform: {platform.system()} {platform.release()}")
    print(f"   Architecture: {platform.machine()}")
    print(f"   Python: {sys.version.split()[0]}")
    
    # Check executable size
    exe_path = Path('dist/AI-Terminal')
    if exe_path.exists():
        total_size = sum(f.stat().st_size for f in exe_path.rglob('*') if f.is_file())
        print(f"   Executable size: {total_size / (1024*1024):.1f} MB")
        print(f"   Location: {exe_path.absolute()}")

def main():
    """Main build function"""
    parser = argparse.ArgumentParser(description='Build AI-Powered SSH Terminal with Ollama')
    parser.add_argument('--build-type', choices=['dir', 'onefile', 'debug'], default='dir',
                       help='Type of build to create')
    parser.add_argument('--no-clean', action='store_true',
                       help='Skip cleaning build directories')
    parser.add_argument('--package', action='store_true',
                       help='Create distribution package after build')
    
    args = parser.parse_args()
    
    print("🚀 AI-Powered SSH Terminal with Ollama - Build System")
    print("=" * 50)
    
    # Check dependencies
    if not check_dependencies():
        return 1
    
    # Check Ollama service
    ollama_available, model_count = check_ollama_service()
    
    # Update spec file
    if not update_spec_file(args.build_type):
        return 1
    
    # Build executable
    if not build_executable(args.build_type, not args.no_clean):
        return 1
    
    # Show build information
    show_build_info()
    
    # Create package if requested
    if args.package:
        create_distribution_package()
    
    print("\n✅ Build process completed!")
    print("\n📋 Next steps:")
    print("1. Test the executable in dist/AI-Terminal/")
    print("2. Run ./dist/AI-Terminal/AI-Terminal (Linux/macOS)")
    print("3. Or run .\\dist\\AI-Terminal\\AI-Terminal.exe (Windows)")
    
    if ollama_available:
        print(f"\n💡 Note: Ollama service detected with {model_count} models")
    else:
        print("\n💡 Note: Install and start Ollama service for AI features")
    
    return 0

if __name__ == "__main__":
    sys.exit(main())